from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.common import jwt
from app.crud.base import CRUDBase
from app.models.user import User
from app.schemas.auth import AuthRegisterSchema
from app.schemas.user import CreateUserParam, UpdateUserParam
from app.utils.captcha import text_captcha


class CRUDUser(CRUDBase[User, CreateUserParam, UpdateUserParam]):
    async def get(self, db: AsyncSession, pk: int) -> User | None:
        return await self.get_(db, pk=pk)

    async def get_by_username(self, db: AsyncSession, username: str) -> User | None:
        stmt = select(self.model).where(self.model.username == username)
        user = await db.execute(stmt)
        return user.scalars().first()

    async def create(self, db: AsyncSession, obj: AuthRegisterSchema) -> None:
        salt = text_captcha(5)
        obj.password = await jwt.get_hash_password(f"{obj.password}{salt}")
        dict_obj = obj.model_dump()
        dict_obj.update({"salt": salt})
        new_user = self.model(**dict_obj)
        db.add(new_user)


user_dao: CRUDUser = CRUDUser(User)
